# Author:kilien
# Leetcode 141.Linked List Cycle
# 思路1：使用set记录链表元素，重复即有环
# time:O(n) space:O(n)
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        key = set()
        while head:
            if head in key:
                return True
            else:
                key.add(head)
            head = head.next
        return False


# 思路2：使用快慢指针，当两者相遇则有环
# time：O(n) space:O(1)

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        fast = slow = head
        while fast and slow and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast is slow:
                return True     
        return False